package com.wenzhoujie.utils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;

public class SDHandlerUtil
{

	private static Handler handler = new Handler(Looper.getMainLooper());

	public static void runOnUiThread(Runnable r)
	{
		handler.post(r);
	}

	public static void runOnUiThreadFrontOfQueue(Runnable r)
	{
		handler.postAtFrontOfQueue(r);
	}

	public static void runOnUiThreadAtTime(Runnable r, long uptimeMillis)
	{
		handler.postAtTime(r, uptimeMillis);
	}

	public static void runOnUiThreadAtTime(Runnable r, Object msgObj, long uptimeMillis)
	{
		handler.postAtTime(r, msgObj, uptimeMillis);
	}

	public static void runOnUiThreadDelayed(Runnable r, long delayMillis)
	{
		handler.postDelayed(r, delayMillis);
	}

	/**
	 * callBack的方法会在UI线程被调用
	 * 
	 * @param msg
	 * @param callBack
	 */
	public static boolean sendMessage(final Message msg, final Callback callBack)
	{
		if (callBack != null && msg != null)
		{
			if (Looper.myLooper() == Looper.getMainLooper())
			{
				callBack.handleMessage(msg);
			} else
			{
				runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						callBack.handleMessage(msg);
					}
				});
			}
			return true;
		}
		return false;
	}

	public static boolean sendMessage(Message msg, Handler handler)
	{
		if (handler != null && msg != null)
		{
			return handler.sendMessage(msg);
		}
		return false;
	}

	public Message obtainMessage()
	{
		return Message.obtain();
	}

	public Message obtainMessage(int what)
	{
		return obtainMessage(what, null, 0, 0);
	}

	public Message obtainMessage(int what, Bundle data)
	{
		Message msg = obtainMessage(what);
		msg.setData(data);
		return msg;
	}

	public Message obtainMessage(int what, int arg1)
	{
		return obtainMessage(what, null, arg1, 0);
	}

	public Message obtainMessage(int what, int arg1, int arg2)
	{
		return obtainMessage(what, null, arg1, arg2);
	}

	public Message obtainMessage(int what, Object obj)
	{
		return obtainMessage(what, obj, 0, 0);
	}

	public Message obtainMessage(int what, Object obj, int arg1)
	{
		return obtainMessage(what, obj, arg1, 0);
	}

	public Message obtainMessage(int what, Object obj, int arg1, int arg2)
	{
		Message msg = obtainMessage();
		msg.what = what;
		msg.obj = obj;
		msg.arg1 = arg1;
		msg.arg2 = arg2;
		return msg;
	}

}
